//
//  OrderListController.swift
//  vmes
//
//  Created by user on 2021/10/26.
//

import UIKit
import Alamofire
import Toast
import ESPullToRefresh
import AVFoundation
import EmptyPage

class OrderListController : BaseController,UITableViewDelegate,UITableViewDataSource,LBXScanViewControllerDelegate, UITextFieldDelegate {
    
    var equidId:String?
    var machineInfo:MachineItem?
    var scanResult:ScanCode?
    
    //存储选中单元格的索引
    var selectedIndexs = [Int]()
    //    var mulityOpen:Bool=false
    var currentItem:Int?
    
    //    var value : [JSON] = []//result数组
    var dataArr :[OrderItem] = []//数据源
    var originArr :[OrderItem] = []//数据源
    var selectArray :[OrderItem] = []//选择数据数组
    
    //    var dataArr = NSMutableArray()//数据源
    let imageView = UIImageView()
    let machineNameLb=UILabel()
    let workshopLb=UILabel()
    let desc1=UILabel()
    let desc2=UILabel()
    let statusLb=UILabel()
    let tableView = UITableView()
    
    //多单开工按钮
    lazy var rightBtn: UIButton = {
        let btn = UIButton()
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        btn.setTitle("多单开工", for: .normal)//默认为编辑
        //        btn.setTitle("提交", for: .selected)//点击之后为完成
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.setTitleColor(UIColor.white, for: .selected)
        btn.isHidden=true
        btn.addTarget(self, action: #selector(rightBtnAction), for: .touchUpInside)
        return btn
    }()
    
    //取消按钮
    lazy var cancelBtn: UIButton = {
        let btn = UIButton()
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        btn.setTitle("取消", for: .normal)//默认为取消
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.addTarget(self, action: #selector(cancelBtnAction), for: .touchUpInside)
        return btn
    }()
    
    @objc func rightBtnAction(){
        if rightBtn.currentTitle == "多单开工"{
            rightBtn.setTitle("提交", for: .normal)//默认为编辑
            //如果点击编辑按钮，则rightBtn.isSelected为true，加载删除button
            self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: cancelBtn)
            tableView.setEditing(true, animated: true)//设置myTableView为可编辑状态
            tableView.allowsSelectionDuringEditing=true
            tableView.allowsMultipleSelection=true
        }else{
            //提交之前需要做一些判断
            print(selectArray.count)
            if selectArray.count < 2{
                self.view.makeToast("请至少选择两条工单！")
                return
            }
            for item in dataArr {
                if ("1"==item.statusFlag){
                    self.view.makeToast("当前已有工单开工！")
                    return;
                }
                if (item.tbBShiftWork != nil && item.tbBShiftWork?.batchNumber != "") {
                    if ("2"==(item.tbBShiftWork?.workType)){
                        continue;
                    }
                    self.view.makeToast("当前已有多单开工")
                    return;
                }
            }
            //else则为再次点击，恢复成原状，把删除button移除，设置myTableView为不可编辑状态，如果不移除删除button，删除button会占用navigationController的默认返回按钮
            openBottomBatchDialog()
        }
    }
    
    @objc func cancelBtnAction(){
        rightBtn.setTitle("多单开工", for: .normal)//默认为编辑
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "icon_back"), style: .plain, target: self, action: #selector(backItemPressed))
        tableView.setEditing(false, animated: true)
        self.selectArray.removeAll()
        
    }
    
    
    
    override func viewWillAppear(_ animated: Bool) {
        navigationController?.navigationBar.tintColor = .white
        navigationController?.setNavigationBarHidden(false, animated: true)
        //设置navigationItem.rightBarButtonItems为编辑，全选，默认不加载删除按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        if machineInfo != nil {
            getOrderData()
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //        let item = UIBarButtonItem(title: "返回", style: .plain, target: self, action:#selector(backItemPressed))
        //        item.image = UIImage(named: "icon_back")
        //        self.navigationItem.leftBarButtonItem = item
        self.navigationItem.title="机器1"
        //修改NavigationBar title的属性
        //        let dict:NSDictionary = [NSAttributedString.Key.foregroundColor: UIColor.white]
        //        self.navigationController?.navigationBar.titleTextAttributes = dict as? [NSAttributedString.Key : Any]
        if machineInfo != nil {
            self.navigationItem.title=machineInfo?.equipCode
        }
        self.view.backgroundColor = UIColor.colorWithHex(hexStr: "#0FA386")
        
        let topLayout=UIView()
        //        topLayout.alpha=0.2
        topLayout.backgroundColor = UIColor.colorWithHex(hexStr: "#3FB59E",alpha: 1)
        topLayout.layer.shadowColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.5).cgColor
        topLayout.frame=CGRect(x: 10, y: statusBarHeight, width: width-20, height: 275)
        topLayout.roundCorners([.topLeft,.topRight], radius: 10)
        topLayout.layer.shadowOpacity = 1
        topLayout.layer.shadowRadius = 1.5
        view.addSubview(topLayout)
        
        let searchEdittext=UITextField()
        
        topLayout.addSubview(searchEdittext)
        searchEdittext.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(40)
        }
        searchEdittext.layer.cornerRadius=20
        searchEdittext.delegate = self
        searchEdittext.placeholder = "输入工单号进行搜索"
        searchEdittext.returnKeyType = .search
        let leftView = UIView()
        leftView.frame = CGRect(x: 5, y: 0, width: 35, height: 35)
        let imgV = UIImageView(image: UIImage(systemName: "magnifyingglass"))
        imgV.frame = leftView.bounds
        imgV.contentMode = .center
        leftView.addSubview(imgV)
        
        searchEdittext.leftView = leftView
        //设置为空内容才显示放大镜，输入时不显示放大镜.unlessEditing  如要一直显示设置.always
        searchEdittext.leftViewMode = .always
        
        searchEdittext.backgroundColor = UIColor.colorWithHex(hexStr: "#0FA386")
        
        let nameLb=UILabel()
        nameLb.text="翟志鹏"
        nameLb.textColor = .white
        topLayout.addSubview(nameLb)
        let roleLb=SHLabel()
        roleLb.textInsets=UIEdgeInsets(top: 3, left: 10, bottom: 3, right: 10)
        topLayout.addSubview(roleLb)
        //        let exitBtn=UILabel()
        //        exitBtn.text="退出"
        //        topLayout.addSubview(exitBtn)
        let companyLb=UILabel()
        companyLb.text="苏州测绘地理信息有限公司"
        companyLb.textColor = .white
        companyLb.font=companyLb.font.withSize(15)
        topLayout.addSubview(companyLb)
        nameLb.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(15)
            make.top.equalTo(searchEdittext.snp.bottom).offset(20)
        }
        companyLb.snp.makeConstraints { make in
            make.top.equalTo(nameLb.snp.bottom).offset(15)
            make.left.equalToSuperview().offset(15)
        }
        
        roleLb.textColor = .white
        roleLb.layer.cornerRadius=12
        roleLb.font=roleLb.font.withSize(14)
        roleLb.layer.backgroundColor = UIColor.colorWithHex(hexStr: "#ffffff", alpha: 0.2).cgColor
        roleLb.snp.makeConstraints { make in
            make.left.equalTo(nameLb.snp.right).offset(20)
            make.bottom.equalTo(nameLb.snp.bottom)
        }
        //        exitBtn.textColor = .white
        //        exitBtn.font=exitBtn.font.withSize(15)
        //        exitBtn.alpha=0.5
        //        exitBtn.snp.makeConstraints { make in
        //            make.top.equalToSuperview().offset(20)
        //            make.right.equalToSuperview().offset(-10)
        //        }
        let userInfo = K.userInfo
        nameLb.text=userInfo?.nickName
        roleLb.text=userInfo?.post?.postName
        companyLb.text=userInfo?.company?.companyName
        
        
        let line = UIView()
        line.backgroundColor = .black
        line.alpha=0.2
        topLayout.addSubview(line)
        line.snp.makeConstraints { make in
            make.top.equalTo(companyLb.snp.bottom).offset(10)
            make.width.equalTo(topLayout.snp.width)
            make.height.equalTo(0.3)
        }
        
        imageView.backgroundColor=UIColor.colorWithHex(hexStr: "#9FDACE")
        imageView.image = imageWithImage(image: UIImage(named: "machine")!, scaledToSize: CGSize(width: 100, height: 80))
        imageView.contentMode = .center
        topLayout.addSubview(imageView)
        imageView.snp.makeConstraints { make in
            make.top.equalTo(line.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(10)
            make.width.height.equalTo(120)
        }
        
        
        machineNameLb.font=machineNameLb.font.withSize(22)
        machineNameLb.textColor = .white
        machineNameLb.text="J001"
        topLayout.addSubview(machineNameLb)
        machineNameLb.snp.makeConstraints { make in
            make.left.equalTo(imageView.snp.right).offset(20)
            make.top.equalTo(imageView.snp.top)
        }
        
        workshopLb.font=machineNameLb.font.withSize(15)
        workshopLb.textColor = .white
        workshopLb.text="车间1"
        topLayout.addSubview(workshopLb)
        workshopLb.snp.makeConstraints { make in
            make.left.equalTo(machineNameLb.snp.left)
            make.top.equalTo(machineNameLb.snp.bottom).offset(5)
        }
        
        desc1.font=machineNameLb.font.withSize(15)
        desc1.alpha=0.8
        desc1.textColor = .white
        desc1.text="J001"
        topLayout.addSubview(desc1)
        desc1.snp.makeConstraints { make in
            make.left.equalTo(machineNameLb.snp.left)
            make.top.equalTo(workshopLb.snp.bottom).offset(20)
        }
        
        desc2.font=machineNameLb.font.withSize(15)
        desc2.textColor = .red
        desc2.alpha=0.8
        desc2.text="J001"
        topLayout.addSubview(desc2)
        desc2.snp.makeConstraints { make in
            make.left.equalTo(machineNameLb.snp.left)
            make.top.equalTo(desc1.snp.bottom).offset(5)
        }
        
        
        statusLb.backgroundColor = UIColor.colorWithHex(hexStr: "#FD8D19")
        statusLb.textColor = .white
        statusLb.text=textVertical(oldStr: "待机")
        statusLb.font = .systemFont(ofSize: 15)
        statusLb.numberOfLines=0
        statusLb.textAlignment = .center
        statusLb.lineBreakMode = .byCharWrapping
        topLayout.addSubview(statusLb)
        statusLb.snp.makeConstraints { make in
            make.top.equalTo(line.snp.bottom)
            make.right.equalToSuperview().offset(-10)
            make.width.equalTo(35)
            make.height.equalTo(50)
        }
        initBottomView()
        //        tableView=UITableView()
        //        let tableView = UITableView(frame: view.bounds, style: .grouped)
        tableView.backgroundColor = .white
        
        tableView.separatorStyle = .none
        tableView.dataSource = self
        tableView.delegate = self
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.width.equalTo(self.width)
            make.bottom.equalToSuperview().offset(-60)
            make.top.equalTo(topLayout.snp.bottom)
        }
        if scanResult != nil{
            let comid=scanResult?.compId ?? ""
            let equipId=scanResult?.equipId ?? ""
            let workshopType=scanResult?.workshopType ?? ""
            getMachineInfo(compId: comid, equipId: equipId, workshopType: workshopType)
        }else{
            let comid=machineInfo?.compId ?? ""
            let equipId=machineInfo?.id ?? ""
            let workshopType=K.currentWorkShop?.workshopType ?? ""
            getMachineInfo(compId: comid, equipId: equipId, workshopType: workshopType)
            //            initMachineInfo()
        }
        self.tableView.es.addPullToRefresh {
            [unowned self] in
            getOrderData()
            /// Do anything you want...
            /// ...
            /// Stop refresh when your job finished, it will reset refresh footer if completion is true
            //            self.tableView.es.stopPullToRefresh(completion: true)
            
        }
        let customEmptyView = MyEmptyView()
        tableView.ep.set(emptyView: customEmptyView)
        initLoadingView()
        
    }
    
    func getMachineInfo(compId: String,equipId: String,workshopType: String){
        spinner.startAnimating()
        let parameters: Dictionary = [
            //            "compId":scanResult?.compId ?? "",
            //            "equipId":scanResult?.equipId ?? "",
            //            "workshopType":scanResult?.workshopType ?? ""
            "compId":compId,
            "equipId":equipId,
            "workshopType":workshopType
        ]
        sessionManager.request(NetInfo.machineDetail, method:.post
                               , parameters:parameters,encoder: JSONParameterEncoder.default,headers: K.headers!).responseJSON { response in
            self.spinner.stopAnimating()
            print(response)
            switch response.result {
            case .success:
                if let data=response.data{
                    let response = try? JSONDecoder().decode(MachineData.self, from: data)
                    if(response?.code==200){
                        self.machineInfo=response?.data
                        self.initMachineInfo()
                        self.getOrderData()
                    }else{
                        self.view.makeToast(response?.msg)
                    }
                }
            case .failure:
                print("ERROR")
                self.view.makeToast("请求失败")
            }
        }
    }
    
    func initMachineInfo(){
        self.equidId=machineInfo?.id
        machineNameLb.text=machineInfo?.equipCode
        workshopLb.text=machineInfo?.workshopName
        desc1.text=machineInfo?.equipName
        desc2.text=machineInfo?.shiftName
        statusLb.text=textVertical(oldStr: machineInfo?.statusName ?? "关机")
        if("G"==machineInfo?.statusValue!){
            statusLb.backgroundColor = UIColor.colorWithHex(hexStr: "#67C23A")
        }else if("Y"==machineInfo?.statusValue!){
            statusLb.backgroundColor = UIColor.colorWithHex(hexStr: "#E6A23C")
        }else if("R"==machineInfo?.statusValue!){
            statusLb.backgroundColor = UIColor.colorWithHex(hexStr: "#E63C3C")
        }else{
            statusLb.backgroundColor = UIColor.colorWithHex(hexStr: "#999999")
        }
    }
    
    func initBottomView(){
        let warnLabel=UILabel()
        let scanLabel=UILabel()
        view.addSubview(warnLabel)
        view.addSubview(scanLabel)
        let attrStr = NSAttributedString(string: "  报警信息", attributes: [.foregroundColor : UIColor.colorWithHex(hexStr: "#FF7B44")])
        // 图文混排
        let attacment = NSTextAttachment()
        attacment.image = UIImage(named: "icon_warn")
        // 获取文字字体
        let font = warnLabel.font
        attacment.bounds = CGRect(x: 0, y: -4, width: (font?.lineHeight)!, height: (font?.lineHeight)!)
        let attrImageStr = NSAttributedString(attachment: attacment)
        let attrMStr = NSMutableAttributedString()
        attrMStr.append(attrImageStr)
        attrMStr.append(attrStr)
        warnLabel.attributedText = attrMStr
        warnLabel.backgroundColor = .white
        warnLabel.textAlignment = .center
        warnLabel.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.left.equalToSuperview()
            make.height.equalTo(60)
            make.width.equalTo(width/2)
        }
        
        // 图文混排
        let attrStr2 = NSAttributedString(string: "  切换设备", attributes: [.foregroundColor : UIColor.colorWithHex(hexStr: "#099A80")])
        let attacment2 = NSTextAttachment()
        attacment2.image = UIImage(named: "icon_scan")
        // 获取文字字体
        let font2 = scanLabel.font
        attacment2.bounds = CGRect(x: 0, y: -4, width: (font2?.lineHeight)!, height: (font2?.lineHeight)!)
        let attrImageStr2 = NSAttributedString(attachment: attacment2)
        let attrMStr2 = NSMutableAttributedString()
        attrMStr2.append(attrImageStr2)
        attrMStr2.append(attrStr2)
        scanLabel.attributedText = attrMStr2
        //        scanLabel.text = "切换设备"
        //        scanLabel.textColor=UIColor.colorWithHex(hexStr: "#099A80")
        scanLabel.backgroundColor = .white
        scanLabel.textAlignment = .center
        scanLabel.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo(60)
            make.width.equalTo(width/2)
        }
        warnLabel.isUserInteractionEnabled=true
        warnLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(toWarn)))
        scanLabel.isUserInteractionEnabled=true
        scanLabel.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(scan)))
    }
    
    @objc func toWarn(){
        let vc=WarnListController()
        navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc func scan(){
        ZhiFuBaoStyle()
    }
    
    func ZhiFuBaoStyle() {
        //设置扫码区域参数
        var style = LBXScanViewStyle()
        style.centerUpOffset = 60
        style.xScanRetangleOffset = 30
        if UIScreen.main.bounds.size.height <= 480 {
            //3.5inch 显示的扫码缩小
            style.centerUpOffset = 40
            style.xScanRetangleOffset = 20
        }
        style.color_NotRecoginitonArea = UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 0.4)
        style.photoframeAngleStyle = LBXScanViewPhotoframeAngleStyle.Inner
        style.photoframeLineW = 2.0
        style.photoframeAngleW = 16
        style.photoframeAngleH = 16
        
        style.isNeedShowRetangle = false
        
        style.anmiationStyle = LBXScanViewAnimationStyle.NetGrid
        style.animationImage = UIImage(named: "CodeScan.bundle/qrcode_scan_full_net")
        
        let vc = LBXScanViewController()
        vc.title="扫码"
        navigationController?.navigationBar.tintColor = .white
        vc.scanStyle = style
        vc.isSupportContinuous = false;
        vc.scanResultDelegate = self
        self.navigationController?.pushViewController(vc, animated: false)
        
    }
    
    func scanFinished(scanResult: LBXScanResult, error: String?) {
        NSLog("scanResult:\(scanResult)")
        let str=scanResult.strScanned!
        self.scanResult = try? JSONDecoder().decode(ScanCode.self, from:  str.data(using: .utf8)!)
        if(self.scanResult?.workshopId == K.currentWorkShop?.workshopId){
            let comid=self.scanResult?.compId ?? ""
            let equipId=self.scanResult?.equipId ?? ""
            let workshopType=self.scanResult?.workshopType ?? ""
            getMachineInfo(compId: comid, equipId: equipId, workshopType: workshopType)
        }else{
            self.view.makeToast("数据错误")
        }
    }
    
    func formatTime(str:String) -> String{
        if(str.isEmpty||str.count<15){
            return str
        }
        let index=str.index(str.startIndex, offsetBy: 5);
        let index2=str.index(str.startIndex, offsetBy: 15);
        return String(str[index...index2])
    }
    
    //MARK: UITableViewDataSource
    // cell的个数
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArr.count
    }
    
    // UITableViewCell
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cellid = "testCellID"
        var cell = tableView.dequeueReusableCell(withIdentifier: cellid) as? OrderCell
        if cell==nil {
            cell = OrderCell(style: .default, reuseIdentifier: cellid)
        }
        let item = dataArr[indexPath.row]
        cell?.orderData=item
        cell?.nameLabel.text="工单:"+item.workorderCode!
        cell?.descLabel.text="产品编号："+(item.productCode ?? "无")
        if(item.procedureType != nil){
            cell?.typeLabel.text=(item.procedureType ?? "")+" "+(item.procedureNo ?? "")
        }
        
        cell?.classLabel.text=item.tbBShiftWork?.className ?? ""
        cell?.productLabel.text="产品名称："+(item.productName ?? "无")
        cell?.materialLabel.text=item.materialText == nil ? "物料材质：空":"物料材质：" + item.materialText!
        cell?.materialColorLabel.text=item.materialColo == nil ? "物料颜色：无":"物料颜色：" + item.materialColo!
        
        cell?.planNumLb.text="当班计划量：" + String(item.shiftPlanOutput ?? 0)
        //        cell?.autoNumLb.text="已完成量：" + String(item.workreportOutput ?? 0)
        cell?.allNumLb.text="总计划量：" + String(item.scheduleNumber ?? 0)
        cell?.autoNumLb.text="自" + String(item.acqOutput ?? 0) + " / 手" + String(item.workreportOutput ?? 0)
        
        cell?.timeLabel.text=formatTime(str: item.planStartTime!)+"～"+formatTime(str: item.planEndTime!)
        
        
        if ("0"==item.statusFlag!) { //待生产
            cell?.iconStatus.image = UIImage(named: "icon_wait")
        } else if ("3"==item.statusFlag!) {//已完成
            cell?.iconStatus.image = UIImage(named: "icon_finish")
        } else if ("1"==item.statusFlag!) {//开工
            cell?.iconStatus.image = UIImage(named: "icon_open")
        } else if ("2"==item.statusFlag!) {//完工
            self.view.makeToast("未知状态")
        }
        if cell!.isSelected{
            let index = selectArray.firstIndex(of: item)
            cell?.selectOrder.isHidden=false
            cell?.selectOrder.text=String((index ?? 0)+1)
        }else{
            
        }
        
        if (item.tbBShiftWork == nil || item.tbBShiftWork?.batchNumber == nil) {
            cell?.image.isHidden=true
        } else {
            cell?.image.isHidden=false
            if (item.tbBShiftWork!.isAutoWork == 5) {
                cell?.image.image=UIImage(named: "icon_zhu")
                cell?.selectOrder.text=String(item.tbBShiftWork?.batchOrder ?? 0)
                cell?.selectOrder.isHidden=false
            }else if (item.tbBShiftWork!.isAutoWork == 5||item.tbBShiftWork!.isAutoWork == 6) {
                cell?.image.image=UIImage(named: "icon_batch")
                cell?.selectOrder.isHidden=true
            }else{
                cell?.image.isHidden=true
                cell?.selectOrder.isHidden=true
            }
        }
        
        
        return cell!
    }
    
    //MARK: UITableViewDelegate
    // 设置cell高度
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 125.0
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
        let select = self.dataArr[indexPath.row]
        if (self.selectArray.contains(select)) {
            let index = selectArray.firstIndex(of: select)
            selectArray.remove(at: index!)
        }
        //        tableView.reloadData()
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true//返回可编辑
    }
    
    func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
        //这里非常关键！
        return UITableViewCell.EditingStyle(rawValue: UITableViewCell.EditingStyle.delete.rawValue | UITableViewCell.EditingStyle.insert.rawValue)!
    }
    
    // 选中cell后执行此方法
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if tableView.isEditing {
            tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
            let select = self.dataArr[indexPath.row]
            if (!self.selectArray.contains(select)) {
                self.selectArray.append(select)
            }
            //            self.tableView.reloadRows(at: [indexPath], with: .automatic)
            //            tableView.reloadData()
        }else{
            currentItem=indexPath.row
            //判断职位
            let postCode=K.userInfo?.post?.postCode ?? "9999"
            let item=dataArr[indexPath.row]
            if ("0"==item.statusFlag!) { //待生产
                if ("9903" != postCode) {//质检
                    startWork();
                }
            } else if ("3"==item.statusFlag!) {//已完成
                if (item.tbBShiftWork != nil && item.tbBShiftWork?.isAutoWork == 5) {
                    openBottomDialog(open_status: 2);
                    return
                }
                if ("9999" != postCode) {//操作工
                    inspectWork();
                }
            } else if ("1"==item.statusFlag!) {//开工
                if (item.tbBShiftWork != nil && item.tbBShiftWork?.isAutoWork == 5) {
                    openBottomDialog(open_status: 2);
                    return
                }
                if ("9903"==postCode) {//质检
                    inspectWork();
                } else if ("9999"==postCode) {//操作工
                    finishWork();
                } else { //管理人员
                    openBottomDialog(open_status: 3)
                }
            } else if ("2"==item.statusFlag!) {//完工
                if ("9903"==postCode) {//质检
                    inspectWork();
                } else if ("9999"==postCode) {//操作工
                    startWork();
                } else { //管理人员
                    openBottomDialog(open_status: 1)
                }
            } else {
                self.view.makeToast("未知状态")
            }
        }
        
        
    }
    
    func textVertical(oldStr:String)->String{
        var newStr:String = ""
        for charstr in oldStr{
            newStr.append(charstr)
            newStr.append("\n")
        }
        return newStr
    }
    
    func imageWithImage(image: UIImage, scaledToSize: CGSize) -> UIImage? {
        //UIGraphicsBeginImageContext(newSize);
        // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
        // Pass 1.0 to force exact pixel size.
        let radio = image.size.width / image.size.height
        UIGraphicsBeginImageContextWithOptions(scaledToSize, false, 0.0)
        image.draw(in: CGRect(x: 0, y: 0, width: scaledToSize.width * radio, height: scaledToSize.height))
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage
    }
    
    func getOrderData(){
        spinner.startAnimating()
        let comyId:String=K.userInfo?.company?.companyId ?? ""
        let parameters: Dictionary = [
            "pageNum" : "1",
            "pageSize":"99",
            "compId":comyId,
            "equipId":self.equidId,
            "workshopId": K.currentWorkShop?.workshopId ?? "",
            "workshopType":K.currentWorkShop?.workshopType ?? ""
        ]
        
        sessionManager.request(NetInfo.orderList, method:.post
                               , parameters:parameters,encoder: JSONParameterEncoder.default,headers: K.headers!).responseJSON { response in
            self.spinner.stopAnimating()
            //            print(response)
            self.tableView.es.stopPullToRefresh()
            switch response.result {
            case .success:
                if let data=response.data{
                    let response = try? JSONDecoder().decode(OrderList.self, from: data)
                    if(response?.code==200){
                        self.dataArr.removeAll()
                        self.dataArr.append(contentsOf: (response?.rows)!!)
                        self.dataArr.reverse()
                        self.originArr.removeAll()
                        self.originArr.append(contentsOf: (self.dataArr))
                        var flag:Bool = false;
                        for item in self.dataArr{
                            if (item.tbBShiftWork != nil && item.tbBShiftWork?.batchNumber != "") {
                                if ("2"==(item.tbBShiftWork?.workType)){
                                    continue;
                                }
                                flag=true
                                break
                            }
                        }
                        if flag {
                            self.rightBtn.isHidden=true
                        }else{
                            print("abc")
                            self.rightBtn.isHidden=false
                        }
                        self.tableView.reloadData()
                    }else{
                        self.view.makeToast(response?.msg)
                    }
                }
            case .failure:
                print("ERROR")
                self.view.makeToast("请求失败")
            }
        }
    }
    
    func openBottomDialog(open_status:Int){
        var alert: UIAlertController!
        alert = UIAlertController(title: "", message: "请选择工单对应操作", preferredStyle: .actionSheet)
        let cleanAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        
        let startAction = UIAlertAction(title: "开工", style: .default, handler: {action in self.startWork()})
        let finishAction = UIAlertAction(title: "完工", style: .default, handler: {action in self.finishWork()})
        let inspectAction = UIAlertAction(title: "质检", style: .default, handler: {action in self.inspectWork()})
        let repaireAction = UIAlertAction(title: "补录", style: .default, handler: {action in self.repaireWork()})
        
        alert.addAction(cleanAction)
        if(open_status==1){
            alert.addAction(startAction)
        }else if(open_status==2){
            alert.addAction(repaireAction)
        }else{
            alert.addAction(finishAction)
        }
        alert.addAction(inspectAction)
        
        self.present(alert, animated: true, completion: nil)
    }
    
    func openBottomBatchDialog(){
        var alert: UIAlertController!
        alert = UIAlertController(title: "", message: "请选择开工方式", preferredStyle: .actionSheet)
        let cleanAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
        
        let action1 = UIAlertAction(title: "逐个开工、自动完工", style: .default, handler: {action in self.startBatchWork(type: 5)})
        let action2 = UIAlertAction(title: "同时开工、自动完工", style: .default, handler: {action in self.startBatchWork(type: 6)})
        let action3 = UIAlertAction(title: "同时开工、手动完工", style: .default, handler: {action in self.startBatchWork(type: 7)})
        
        alert.addAction(cleanAction)
        alert.addAction(action1)
        alert.addAction(action2)
        alert.addAction(action3)
        self.present(alert, animated: true, completion: nil)
    }
    
    @objc func startWork(){
        if currentItem != nil{
            //start 之前得判断列表是否已经存在开工的单子
            for item  in dataArr {
                let ii = item
                if ("1" == ii.statusFlag) {
                    self.view.makeToast("当前已有工单开工！");
                    return;
                }
            }
            //判断机器状态是否可以开工
            //            if ("G"==machineInfo?.statusValue || "Y"==machineInfo?.statusValue) { //生产
            let startVc = WorkStartViewController()
            startVc.orderInfo=dataArr[currentItem!]
            //            print(startVc.orderInfo)
            navigationController?.pushViewController(startVc, animated: true)
            //            } else {
            //                self.view.makeToast("当前机器状态无法开工！");
            //            }
        }
    }
    
    @objc func startBatchWork(type:Int){
        spinner.startAnimating()
        var list:[[String:String]]=[]
        for item in selectArray{
            //            let model = BatchModel(compId: (K.userInfo?.company?.companyId)!, scheduleId: (item.id)!,
            //                                   startOperator: (K.userInfo?.userId)!, workorderCode: (item.workorderCode)!
            //                                   , shiftPlanOutput: String(item.shiftPlanOutput!), workshopId: (K.currentWorkShop?.workshopId)!)
            let modelDict:[String:String] = ["compId":(K.userInfo?.company?.companyId)!, "scheduleId":(item.id)!, "startOperator":(K.userInfo?.userId)!,"workorderCode":(item.workorderCode)!,"shiftPlanOutput":String(item.shiftPlanOutput!),"workshopId":(K.currentWorkShop?.workshopId)!]
            list.append(modelDict)
        }
        //        let encoder = JSONEncoder()
        //        encoder.outputFormatting = .prettyPrinted //输出格式好看点
        //        let data = try! encoder.encode(list)
        let parameters: Dictionary<String,Any> = [
            "batchType" : String(type),
            "params" : list
        ]
        print(parameters)
        
        AF.request(NetInfo.batchWork, method:.post
                   , parameters:parameters,encoding: JSONEncoding.default,headers: K.headers!,
                   requestModifier: { $0.timeoutInterval = 5 })
        .responseJSON { (response) in
            self.spinner.stopAnimating()
            print(response)
            switch response.result {
            case .success:
                if let data=response.data{
                    let response = try? JSONDecoder().decode(LoginInfo.self, from: data)
                    if(response?.code==200){
                        self.cancelBtnAction()
                        self.getOrderData()
                        self.view.makeToast("多单开工成功",duration:2)
                        //                        self.perform(#selector(self.backItemPressed), with: nil, afterDelay: 2)
                    }else{
                        self.view.makeToast(response?.msg)
                    }
                }
            case .failure:
                print("ERROR")
                self.view.makeToast("请求失败")
            }
        }
        
    }
    
    
    @objc func finishWork(){
        if currentItem != nil{
            let startVc = WorkFinishController()
            startVc.orderInfo=dataArr[currentItem!]
            navigationController?.pushViewController(startVc, animated: true)
        }
    }
    
    @objc func inspectWork(){
        if currentItem != nil{
            let startVc = WorkQualityController()
            startVc.orderInfo=dataArr[currentItem!]
            navigationController?.pushViewController(startVc, animated: true)
        }
    }
    
    @objc func repaireWork(){   // 补录
        if currentItem != nil{
            let startVc = WorkRepaireController()
            startVc.orderInfo=dataArr[currentItem!]
            navigationController?.pushViewController(startVc, animated: true)
        }
    }
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        return true
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        let s=textField.text! as String
        self.dataArr.removeAll()
        if s.isEmpty{ //判断输入的搜索是否为空
            self.dataArr.append(contentsOf: self.originArr)
        }else{
            for item in self.originArr{
                if item.workorderCode!.lowercased().contains(s.lowercased()){
                    self.dataArr.append(item)
                }
            }
        }
        self.tableView.reloadData()
        textField.hideKeyboard()
        return true
    }
    
    
}
